#!/usr/bin/python

if __name__ == '__main__':
    import sys
    import os

import string
import subprocess
from ConfigParser import RawConfigParser as IniParser
import time
sys.path.append('/backup/opensource-code/python_src/base/')
from fork_exec import fork_exec

Part1=( 'BaseInfo', 'basepath' )
Part2=( 'Command', 'basecommand', 'argv1', 'argv2' )
Part3=( 'Component', 'latin', 'hw', 'py', 'switch' )
Part=( Part1, Part2, Part3 )
class IniFile():
    def __init__( self, file ):
        self.__cfg = IniParser()
        self.__cfg.readfp( open(file) )
    
    def get_command( self ):
        ret = []
        for item in Part:
            section = item[0]
            if True==self.__cfg.has_section( section ):
                for option in item[1:]:
                    if True==self.__cfg.has_option( section, option ):
                        pass
                    else:
                        print 'In the config file, the section:%s is not exists' %option
                        return None
            else:
                print 'In the config file, the section: %s is not exists' %section
                return None

        exec_command = []
        for option in Part2[1:]:
            exec_command.append( self.__cfg.get( Part2[0], option ) )
        component = []
        basepath = self.__cfg.get( Part1[0], Part1[1] )
        basepath = os.path.expanduser( basepath )
        basepath += '/'
        for option in Part3[1:]:
            this_component = option + ':' + basepath + self.__cfg.get( Part3[0], option )
            component.append( this_component )

        ret.append( exec_command )
        ret.append( component )

        return ret

def update( command, component ):
    exec_command = command
    exec_command.append( component )
    #try:
     #   print '===== Begin update component =====' 
      #  print component
       # proc = subprocess.Popen(exec_command, stdin=subprocess.PIPE)
        #if 0==proc.wait():
         #   print '===== End update component ====='
          #  return True
        #else:
         #   return False
    #except OSError, e:
     #   print 'fatal: update component %s failed' %component
      #  return False
    fork_exec( exec_command )

CONFIG_FILE = '/backup/opensource-code/python_src/download/update_config.ini'
def main( argv ):
    if False==os.path.exists( CONFIG_FILE ):
        print >>sys.stderr, 'fatal: config file: %s is not exist' %CONFIG_FILE
        return None

    p = IniFile(CONFIG_FILE)
    result = p.get_command()
    if None==result:
        print >>sys.stderr, 'fatal: parser config file error '
        return None

    component = []
    for item in result[1]:
        component.append( item.split(':')[0] )

    if 0!=len(argv) and '-h'!=argv[0]:
        if argv[0] in component:
            for item in result[1]:
                component_name, component_path = item.split(':')
                if argv[0]==component_name:
                    update( result[0], component_path )
                    return True
        elif 'all'==argv[0]:
            for item in result[1]:
                component_name, component_path = item.split(':')
                update( result[0], component_path )
                time.sleep( 5 )
            return True
    else:
        print 'You can update the component:'
        for eachitem in component:
            print '  \'%s\'' %eachitem
        print '  \'all\' to update all component'
        print '  \'-h\'  for help'
    
    return True

if __name__ == '__main__':
    main(sys.argv[1:])
    #parser = IniFile( CONFIG_FILE )
    #print parser.get_command()

